(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.lookup.componentController', componentController);
	componentController.$inject = [ '$scope', '$q', '$filter', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService', 'ajaxServiceFactory' ];
	function componentController($scope, $q, $filter, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, ajaxServiceFactory) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("componentLookup");
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		ctrl.ok = function() {
			if (ctrl.searchCriteria.serviceCode == null) {
					modalService.openErrorDialogs({
						messages : [ 'please select a service first!' ]
					});
					return false;
			}
			if (ctrl.selectedRows == null || ctrl.selectedRows.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'please select a component first!' ]
				});
				return false;
			}
			ctrl.service.companyServCmpts = ctrl.selectedRows;
			
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.service) !== false) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
		ctrl.init = function() {
			ctrl.service = null;
			if (ctrl.dialogsModule.params.service) {
				ctrl.service = ctrl.dialogsModule.params.service;
				ctrl.serviceCodeOptions = {data: [{label: $filter('encode')(ctrl.service.serviceCode) + " - " + ctrl.service.serviceName, value: ctrl.service.serviceCode}]};
			} else {
				var ajaxService = null;
				if (ctrl.dialogsModule.params.isCompany && ctrl.dialogsModule.params.isCompany == 'Y') {
					// if company setup, need only has it's site selected service
					ajaxService = ajaxServiceFactory.buildAjaxService({
						getServices : {
							url : 'do/cda/dataList/companyService',
							method : 'get'
						}
					});	
				} else {
					// site setup, can select all active service
					ajaxService = ajaxServiceFactory.buildAjaxService({
						getServices : {
							url : 'do/cda/dataList/service',
							method : 'get'
						}
					});	
				}
				ajaxService.getServices().then(function(response) {
					var datas = [];
					var services = ctrl.dialogsModule.params.services;
					if (response.data) {
						for (var i = 0; i < response.data.length; i++) {
							var option = response.data[i];
							if (option.value) {
								var exist = false;
								if (services) {
									for (var j = 0; j < services.length; j++) {
										if ($filter('encode')(services[j].serviceCode) == $filter('encode')(option.value) ) {
											exist = true;
											break;
										}
									}
								}
								if (!exist) {
									if (!ctrl.service ) {
										ctrl.service = {};
									}
									if (!ctrl.service.serviceCode) {
										ctrl.service.serviceCode = option.value;
										ctrl.search();
									}
									datas.push(option);
								}								
							}
						}
					}
					ctrl.serviceCodeOptions = {data: datas};
				});
				ctrl.service = {};
				//ctrl.serviceCodeOptions = {data: [{label: 'CDA', value: 'CDA'}, {label: 'DMS', value: 'DMS'}, {label: 'CLS', value: 'CLS'}]};
			}
			ctrl.notifyeventsOptions = {}
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.multiSelect = dialogsModule.params.multiSelect == undefined ? false : dialogsModule.params.multiSelect;
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			
			//for uneditable page.
			if (ctrl.dialogsModule.pageId == 'CDA_LOOKUP_COMPONENTVIEW') {
				ctrl.gridOptions.enableRowHeaderSelection = false;
				ctrl.layoutConfig.formConfigs.component.gridConfigs['serviceCode'].readonly = true;
				ctrl.ok = null;
			}

			ctrl.gridOptions.isRowSelectable = function(row) {
				if (ctrl.dialogsModule.params.service && ctrl.dialogsModule.params.service.companyServCmpts) {
					for (var i = 0; i < ctrl.dialogsModule.params.service.companyServCmpts.length; i++) {
						if ($filter('encode')(ctrl.dialogsModule.params.service.companyServCmpts[i].componentCode) == $filter('encode')(row.entity.componentCode)) {
							row.grid.api.selection.selectRow(row.entity); 
						}
					}
				}
			}
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			
			$scope.$watch('vm.service.serviceCode', function(newValue, oldValue) {	
				if ($filter('encode')(newValue) == $filter('encode')(oldValue) 
						&& ctrl.searchCriteria.list != null && ctrl.searchCriteria.list.length > 0) {
					return;
				}
				ctrl.searchCriteria.serviceCode = $filter('encode')(newValue);
				if (newValue) {					
					authService.viewService(ctrl.service).then(function(response) {
						if (response.data) {
							response.data.serviceCode = newValue;// serviceCode not same with newValue because by encode
							ctrl.service = response.data;
							ctrl.searchCriteria.serviceCode = $filter('encode')(ctrl.service.serviceCode);
							ctrl.search();
						}

					});
				} else {
					ctrl.searchCriteria.serviceCode = '*';
					ctrl.search();
				}

			});
		};

		ctrl.search = function() {
			if (ctrl.searchCriteria.serviceCode) {
				ctrl.searchCriteria.list = [];
				authService.search(ctrl.searchCriteria).then(function(response) {
					angular.merge(ctrl.searchCriteria, response.data);
					gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
				}, angular.noop);				
			}
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);
